﻿// Ajoute la fonction trim comme méthode de l'objet String.
String.prototype.trim = function ()
{ return this.replace(/(^\s*)|(\s*$)/g, ""); }

function GetCramStatus() {
    return $('#model_Status').val();
}

var onDocumentReady = function () {

    var cramStatus = GetCramStatus();

    $('#cbActivity').hide();
    $('#imgCheck').hide();
    $('#imgCancel').hide();
    $('#td_validate').hide();

    var userRole = $('#UserRole').val();
    var valid = userRole == 4;

    if (cramStatus == 1 || valid) {
        $('#imgCancel').click(CancelAddActivity);
        $(':regex(id, ^delete_)').click(DeleteActivity);
        $('#imgCheck').click(AddActivity);
        $('.Day').click(onClickFn);
        $('.Holiday').click(onClickFn);
        $('#imgAddActivity').click(DisplayActivityCombo);
    }
    else {
        $('#trAddActivity').remove();
    }

    // activation ou désactivation de chaque ligne selon le statut
    var idActivitiesCells = $(':regex(id, ^idCramLine)');
    for (var i = 0; i < idActivitiesCells.length; i++) {
        var idActivity = idActivitiesCells[i].name.split(new RegExp("idCramLine_", "g"))[1];

        var lineStatus = $('#StatusCramLine_' + idActivity).val();
        if (lineStatus != 1 && !valid) {
            $('#delete_' + idActivity).hide();
        }
    }

    var regex = "^printcheck_";
    var printcols = $(':regex(id,' + regex + ')');
    printcols.hide();
    $('#checkheader').hide();
    $('#PrintAction').show();
    $('#PrintCramAction').hide();
    $('#CancelAction').hide();

    var status = $('#CramStatus').val();
   
    if (status == 1) {
        $('#td_submit').show();
    }
    else {
        
        $('#td_submit').hide();
    }

    ComputeToolbarButtonsActivity();
}

// Gestion du clic dans une cellule du cram
var onClickFn = function () {

    var split = this.name.split(new RegExp("_", "g"));
    var idActivity = split[2];
    var numDay = split[1];

    var days = $("#hidDays").val();
    var tabDays = days.split(new RegExp(",", "g"));





    var regex = "^Day_" + numDay + "_";
    var clickedCells = $(':regex(id,' + regex + ')');

    // nombre de cellules renseignées (autre que celle clickée)
    var nbFilledCells = 0;

    var otherCell = null;
    for (var i = 0; i < clickedCells.length; i++) {

        var otherSplit = clickedCells[i].name.split(new RegExp("_", "g"));
        var otherIdActivity = otherSplit[2];

        if (!IsAstreinte(otherIdActivity) && clickedCells[i] != this && clickedCells[i].value != "") {

            var val = parseFloat(clickedCells[i].value.replace(",", "."));

            if (val != NaN && val != 0) {
                otherCell = clickedCells[i];
                nbFilledCells += 1;
            }
        }
    }


    var currentVal = 0;
    if (this.value != "") {
        currentVal = parseFloat(this.value.replace(",", "."));
    }

    // cas d'une astreinte
    if (IsAstreinte(idActivity)) {
        this.value = currentVal == 1 ? "" : 1;
        UpdateLineTotal(this);
        return;
    }

    // 2 cellules sont déjà renseignées => on s'arrête
    if (nbFilledCells == 2) {
        return;
    }

    // Si c'est un jour chomé et que l'activité est un congé alors on bloque la saisie
    if (tabDays[numDay - 1] == 0 && IsHoliday(idActivity) && nbFilledCells != 1) {
        return;
    }

    if (nbFilledCells == 0) {
        this.value = currentVal == 1 ? "" : 1;
    }
    else if (nbFilledCells == 1) {
        otherCell.value = currentVal == 0 ? 0.5 : 1;
        this.value = currentVal == 0 ? 0.5 : "";
    }

    UpdateLineTotal(otherCell);
    UpdateLineTotal(this);
    UpdateCramTotal();

}

// Met à jour tous les totaux du cram
function UpdateCramTotal() {

    var regex = "^Total_";
    var linesTotal = $(':regex(id,' + regex + ')');

    var totalWork = 0;
    var totalHolidays = 0;

    for (var i = 0; i < linesTotal.length; i++) {
        if (linesTotal[i].value != "") {

            var idActivity = linesTotal[i].id.split(new RegExp("_", "g"))[1];

            var val = parseFloat(linesTotal[i].value.replace(",", "."));

            if (val != NaN && !IsAstreinte(idActivity)) {
                if (IsHoliday(idActivity)) {
                    totalHolidays += val;
                }
                else {
                    totalWork += val;
                }
            }
        }
    }

    $("#txtTotalWorkedDays").val(totalWork);
    $("#txtTotalHolidays").val(totalHolidays);
}

// Détermine si l'activité est un congé
function IsHoliday(idActivity) {
    var listIdHolidays = $("#listIdHolidays").val();

    var tabHolidays = listIdHolidays.split(new RegExp(",", "g"));

    for (var i = 0; i < tabHolidays.length; i++) {
        if (idActivity == tabHolidays[i].trim()) {
            return true;
        }
    }
    return false;
}

// Détermine si l'activité est une astreinte
function IsAstreinte(idActivity) {
    var listIdHolidays = $("#listIdAstreinte").val();

    var tabHolidays = listIdHolidays.split(new RegExp(",", "g"));

    for (var i = 0; i < tabHolidays.length; i++) {
        if (idActivity == tabHolidays[i].trim()) {
            return true;
        }
    }
    return false;
}

// Met à jour les totaux des activités d'une ligne
function UpdateLineTotal(cell) {
    if (cell == null) return;
    var idActivity = cell.name.split(new RegExp("_", "g"))[2];

    var regex = "^day_[0-9]*_" + idActivity + "$";

    var line = $(':regex(id,' + regex + ')');

    var total = 0;
    for (var i = 0; i < line.length; i++) {
        if (line[i].value != "") {
            var val = parseFloat(line[i].value.replace(",", "."));
            if (val != NaN) {
                total += val;
            }
        }
    }
    var id = "#Total_" + idActivity
    var totalCell = $(id);
    totalCell.val(total);
}

// Affiche la combo de sélection d'une ligne
function DisplayActivityCombo() {
    $("#cbActivity").show();
    $("#imgCheck").show();
    $("#imgAddActivity").hide();
    $("#imgCancel").show();
}


// Affiche la combo de sélection d'une ligne
function CancelAddActivity() {
    $("#cbActivity").hide();
    $("#imgCheck").hide();

    $("#imgAddActivity").show();
    $("#imgCancel").hide();
}

// ajoute une activité
function AddActivity() {
    var idActivity = $("#cbActivity :selected'").val();
    var activityName = $("#cbActivity :selected'").text();
    if (idActivity == null) {
        return;
    }
    
    AddLine(idActivity, activityName);
    CancelAddActivity();
    ComputeToolbarButtonsActivity();
}

// Ajoute une ligne au tableau
function AddLine(activityId, activityName) {

    var days = $("#hidDays").val();
    var tabDays = days.split(new RegExp(",", "g"));

    var line = "<tr id='tr_" + activityId + "'>"
        + "<td id='printcheck_" + activityId + "' class='ReadonlyCellDay' style='display: none;'>"
        + "<input id='selection_" + activityId + "' name='selection_" + activityId + "' type='checkbox' value='true'>"
        + "<input name='selection_" + activityId + "' type='hidden' value='false'>"
        + "</td>"
        + "<td id='addActivity_"+ activityId +"'>" 
        + "<input id='Id' name='idCramLine_" + activityId + "' type='hidden' value='00000000-0000-0000-0000-000000000000'/>"
        + "<img id='delete_" + activityId + "' src='/Content/Images/delete.png' class='Icon' alt=\"Supprimer\" title=\"Supprimer\"/>" 
        + "</td>";

    line += "<td>" + activityName + "</td>";

    for (var i = 0; i < tabDays.length; i++) {

        var className = "Day";
        // jour férié 
        if (tabDays[i] == 0) {
            className = "Holiday"
        }

        line += "<td id='day_" + (i + 1) + "' class='Cell" + className + "'>"
         + "<input MaxLength='3' class='" + className + "' id='day_" + (i + 1) + "_" + activityId + "' name='day_" + (i + 1) + "_" + activityId + "' type='text' value='' readonly = 'readonly' />"
         + "</td>";

    }

    // ajout de la cellule des totaux
    line += "<td class=\"ReadonlyCellDay\"><input id='Total_" + activityId + "' type='text' value='0' class='totalActivity' readonly = 'readonly' />";

    

    line = line + "</tr>";


    var input_name = "idCramLine_" + activityId;
    var test = isLineExist(input_name);

    if (!test) {
        $('#tableCram tr:last').before(line);

        $('.Day').click(onClickFn);
        $('.Holiday').click(onClickFn);
        $(':regex(id, ^delete_)').click(DeleteActivity);
    }
    else {
        alert('Cette activité est déjà pris en compte.');
    }
}

function isLineExist(name) {
    var l = $('input[name =' + name + ']').length;

    if (l != 0)
        return true;
    else
        return false;
}

// Supprime une activité
function DeleteActivity() {

    var idActivity = this.id.split(new RegExp("_", "g"))[1];
    $("#tr_" + idActivity).remove();

    UpdateCramTotal();
    ComputeToolbarButtonsActivity();
}

// Indique si le cram est au moins au statut nouveau
function IsCramNew() {
    return GetCramStatus() == 1;
}

// Recupere un tableau contenant les activités actuellement présentes dans le cram
function GetActivities() {
    // on recupere toutes les lignes du tableau commencant par tr_
    var tr_activities = $(':regex(id, ^tr_)');
    var activities = new Array();
    for (var i = 0; i < tr_activities.length; i++) {
        var tabSplit = tr_activities[i].id.split(new RegExp("_", "g"));
        activities[i] = tabSplit[1];
    }
    return activities;

}

// Determine si le cram posséde au moins un projet qui soit de type astreinte
function HasAstreintes() {
    var activities = GetActivities();
    if (activities.length == 0) {
        return false;
    }

    for (var i = 0; i < activities.length; i++) {
        if(IsAstreinte(activities[i]))
            return true;
    }
    return false;

}

// Determine si le cram posséde au moins un projet qui ne soit pas de type astreinte
function HasProjectOrHolidays() {
    var activities = GetActivities();
    if (activities.length == 0) {
        return false;
    }

    for (var i = 0; i < activities.length; i++) {
        if (!IsAstreinte(activities[i]))
            return true;
    }
    return false;

}

// Calcule l'état d'activation des différents boutons de la barre d'outils
function ComputeToolbarButtonsActivity() {

    HideShowButton($('#td_validate'), false);
    // HideShowButton($('#td_submit'), true); // ???
    HideShowButton($('#CancelAction'), false);
    HideShowButton($('#SaveAction'), true);
    HideShowButton($('#PrintAction'), false);
    HideShowButton($('#PrintCramAction'), false);
    HideShowButton($('#ExportToPdfAction'), !IsCramNew() && HasProjectOrHolidays());
    HideShowButton($('#ExportAstreintesToPdfAction'), !IsCramNew() && HasAstreintes());
}

function HideShowButton(button, show) {
    if (show) {
        button.show();
    }
    else {
        button.hide();
    }
}

// permet de recuperer tous les éléments dont l'id correspond au regex (http://james.padolsey.com/javascript/regex-selector-for-jquery/)
// usage 
// Select all elements with an ID starting a vowel:
//$(':regex(id,^[aeiou])');
//
// Select all DIVs with classes that contain numbers:
//$('div:regex(class,[0-9])');
//
// Select all SCRIPT tags with a SRC containing jQuery:
//$('script:regex(src,jQuery)');
//  
jQuery.expr[':'].regex = function (elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels, '')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}


